<template>
  <div class="map-box">
    <div class="map_menu1">
      <el-radio-group v-model="layerShowType" size="mini" @change="changeLayerShowType">
        <el-radio-button label="baseDT">默认地图</el-radio-button>
        <el-radio-button label="satellite">卫星地图</el-radio-button>
      </el-radio-group>
    </div>
    <div v-if="info.show" class="map" ref="map"></div>
  </div>
</template>

<script>
// import gcoord from 'gcoord'
import { mapState } from 'vuex'
// import { tile2lon, tile2lat, urlEncode } from '@/utils/loadMap'

import XYZ from "ol/source/XYZ";
import 'ol/ol.css';
import Map from 'ol/Map';
import View from 'ol/View';
import ImageLayer from 'ol/layer/Image.js';
import TileLayer from 'ol/layer/Tile.js';
import Projection from 'ol/proj/Projection.js';
import { fromLonLat, transform } from "ol/proj";
import Polygon from "ol/geom/Polygon"
import { LineString } from "ol/geom"
import { Feature } from 'ol';
import TileState from 'ol/TileState'
import { Style, Stroke, Fill, Circle as CircleStyle, Text } from 'ol/style'
import Heatmap from 'ol/layer/Heatmap'; // 导入热力图层

import { Vector as SourceVector } from 'ol/source'
import { Vector as LayerVector } from 'ol/layer'
import Point from 'ol/geom/Point';
import Icon from 'ol/style/Icon';
import Overlay from 'ol/Overlay';
import CarLeftPage from "@/components/MyLeftPage/CarLeftPage"
import CarRightPage from "@/components/MyRightPage/CarRightPage"
import {
  getCity,
  getCompanyByDistrictCode,
} from '@/api/hzMJPT/mainInterface.js';
/*地图，图层*/
let map = null
let loca = null
let massLayer = null
/*点*/
let marker = null
let markerGroup = null
let prev15DayPointLayer = null
/*轨迹、折线*/
let todayLayer = null
let prev15DayLayer = null
/*信息窗体*/
let infoWindow = null
// 卫星,路网
let satellite = null, roadnet = null

let WMS5Layer = null // 卫星2020
let WMS6Layer = null // 卫星2017
let WMS7Layer = null // 企业围栏
const Groups2 = [
  {
    name: '底图',
    color: '',
    tag: 0,
    params: {}
  },
  {
    name: '深色交通矢量',
    color: '#f8022f',
    tag: 1,
    params: {
      url: 'amap://styles/059b381bbc317187b1b2d092414cae3d'
    }
  },
  {
    name: '浅色交通矢量',
    color: '#f8022f',
    tag: 1,
    params: {
      url: 'amap://styles/normal'
    }
  },
  {
    name: '卫星路网底图',
    color: '#f8022f',
    tag: 1,
    params: {}
  },
  {
    name: '企业围栏',
    color: '#f8022f',
    tag: 2,
    params: {
      zIndex: 8,
      LAYERS: 'cycemi:dynamic_region',
      url: 'http://192.168.152.152:9080/geoserver/cycemi/wms?'
    }
  },
  {
    name: '卫星2020',
    color: '#f8022f',
    tag: 2,
    params: {
      zIndex: 2,
      LAYERS: 'BasicTJNew20',
      url: 'http://192.168.152.152:9080/geoserver/wms?'
    }
  },
  {
    name: '卫星2017',
    color: '#f8022f',
    tag: 2,
    params: {
      zIndex: 2,
      LAYERS: 'images:tianjin_4m',
      url: 'http://192.168.152.152:9080/geoserver/images/wms?'
    }
  },
]

export default {
  name: 'MyModalMap',
  data() {
    return {
      map: null,
      dynamicLayer: null,
      pulseLineLayer: null,
      mapStyle: 'amap://styles/grey',
      layerActive: false,
      actives2: '深色交通矢量',
      Groups2,
      iconDevice: require("@/assets/icons/dianwei-1-qingdu.png"),
      key: "d7a71c7ad105f0769725901b428c1a79",
      layers: [],
      layerShowType: 'baseDT',


    }
  },
  props: {
    info: {
      type: Object,
      default: {
        lnglat: [],
        show: false,
        show1: false,
        plateNo: '',
        nav: 0
      }
    }
  },
  watch: {
    "info.show1": {
      handler: function (val, oldval) {

        if (!val) {
          this.cleanupResources(); // 统一清理资源
        } else {

          this.$nextTick(() => {
            const that = this
            window.modalMap = that
            const p1 = getCity().then((data) => {
              const promises = data.data.map((e) => {
                // console.log(JSON.stringify(e.geoJson))
                let city = {
                  name: e.district,
                  value: e.districtCode,
                  label: e.district,
                  districtCode: e.districtCode,
                  geojson: JSON.parse(e.geoJson).coordinates,
                  children: []
                };

                return getCompanyByDistrictCode(e.districtCode).then((companyData) => {
                  companyData.data.forEach((company) => {
                    let company1 = {
                      regionId: company.regionId,
                      value: company.regionId,
                      label: company.regionName,
                      name: company.regionName,
                      geom: company.geoJson,
                      detailedAddress: company.detailedAddress
                    };
                    city.children.push(company1);
                  });
                  city.count = city.children.length;
                  return city;
                });
              });

              return Promise.all(promises).then((cities) => {
                that.enterprises = cities;
                that.options = cities
                return cities;
              });
            })
            const p2 = that.initMap()

            Promise.all([p1, p2]).then(() => {

              that.initCompanyIcon()
              that.initMark()
              that.setPoint()
              // that.handlerChange()
            });

          })
        }
      },
      immediate: true,
    }
  },
  mounted() {


  },
  beforeUnmount() {
    this.cleanupResources(); // 统一清理资源
  },
  methods: {
    changeLayerShowType() {
      if (this.map == undefined) {
        return
      }
      if (this.layers.length < 2) {
        const url_Vector = "http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=" + this.key

        let layer = new TileLayer({
          source: new XYZ({
            url: url_Vector,
            wrapX: false,

          }),

        })
        this.layers.push(layer)
      }
      if (this.layerShowType != 'baseDT') {
        if (this.popupElement && this.popupElement.parentNode === this.map.getViewport()) {
          this.map.getViewport().removeChild(this.popupElement);
        }
        this.map.getLayers().setAt(0, this.layers[1]);
      }
      else {
        if (this.popupElement && this.popupElement.parentNode === this.map.getViewport()) {
          this.map.getViewport().removeChild(this.popupElement);
        }
        this.map.getLayers().setAt(0, this.layers[0]);
      }
    },
    cleanupResources() {
      // 1. 停止脉冲动画
      if (this.pulseLineLayer) {
        this.pulseLineLayer.stopAnimation(); // 调用图层的停止方法
        this.map.removeLayer(this.pulseLineLayer); // 从地图移除图层
        this.pulseLineLayer = null;
      }
      if (this.pLayer) {
        this.map.removeLayer(this.pLayer); // 从地图移除图层
        this.pLayer = null;

      }
      // 2. 清理地图实例（如有必要）
      if (this.map) {
        this.map.setTarget(null); // 解除地图与 DOM 的绑定
        this.map = null;
      }


    }, cleanupResources1() {
      // 1. 停止脉冲动画
      if (this.pulseLineLayer) {
        this.pulseLineLayer.stopAnimation(); // 调用图层的停止方法
        this.map.removeLayer(this.pulseLineLayer); // 从地图移除图层
        this.pulseLineLayer = null;
      }
      if (this.pLayer) {
        this.map.removeLayer(this.pLayer); // 从地图移除图层
        this.pLayer = null;

      }
      // 2. 清理地图实例（如有必要）

    },
    initMark() {
      const url_Vector_MARK = "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + this.key
      let layer2 = new TileLayer({
        source: new XYZ({
          url: url_Vector_MARK,
          wrapX: false

        }),
      })

      this.map.addLayer(layer2)
    },
    /**
 * 创建OpenLayers脉冲线图层
 * @param {Array} coordinates - 轨迹坐标数组
 * @returns {ol.layer.Vector} - 脉冲线图层
 */
    /**
  * 创建带有脉冲动画效果的轨迹线图层
  * @param {Array} coordinates - 轨迹坐标数组
  * @returns {ol.layer.Vector} - 脉冲线图层
  */
    createPulseLineLayer(coordinates) {
      // 创建轨迹线要素
      const lineFeature = new Feature({
        geometry: new LineString(coordinates)
      });

      // 创建矢量数据源
      const source = new SourceVector({
        features: [lineFeature]
      });

      // 脉冲动画的状态变量
      let animationState = {
        lineDashOffset: 0,
        isAnimating: true
      };

      // 创建脉冲线图层
      const pulseLineLayer = new LayerVector({
        source: source,
        zIndex: 99,
        style: (feature, resolution) => {
          // 基础线样式
          const baseStyle = new Style({
            stroke: new Stroke({
              color: '#808080',
              width: 4
            })
          });

          // 脉冲线样式，使用当前动画状态
          const pulseStyle = new Style({
            stroke: new Stroke({
              color: '#00ffff',
              width: 4,
              lineDash: [100, 300],
              lineDashOffset: animationState.lineDashOffset
            })
          });

          return [baseStyle, pulseStyle];
        }
      });

      this.pulseLineLayer = pulseLineLayer
      // 动画函数 - 使用requestAnimationFrame实现平滑动画
      const animate = () => {
        if (!animationState.isAnimating) return;

        // 更新动画状态
        animationState.lineDashOffset -= 4;
        if (animationState.lineDashOffset < -400) {
          animationState.lineDashOffset = 0;
        }

        // 触发图层刷新
        pulseLineLayer.changed();


        // 继续下一帧
        requestAnimationFrame(animate);
      };

      // 开始动画
      animate();

      // 添加停止动画的方法（可选）
      pulseLineLayer.stopAnimation = () => {
        animationState.isAnimating = false;
      };

      return pulseLineLayer;
    },
    /**
 * 基于终点坐标生成车辆行驶轨迹
 * @param {Array} endCoord - 终点坐标 [x, y]，使用EPSG:3857投影
 * @param {number} [distance=2000] - 轨迹总长度，单位为米
 * @param {number} [points=15] - 生成的轨迹点数量
 * @returns {Array} - 生成的轨迹坐标数组
 */
    generateVehicleTrack(endCoord, distance = 2000, points = 15) {
      const [endX, endY] = endCoord;
      const track = [];

      // 随机生成起点，位于终点周围的一个区域内
      const startAngle = Math.random() * Math.PI * 2;
      const startDistance = distance * (0.7 + Math.random() * 0.3);
      const startX = endX + Math.cos(startAngle) * startDistance;
      const startY = endY + Math.sin(startAngle) * startDistance;

      // 添加起点
      track.push([startX, startY]);

      // 生成中间点，形成一条平滑曲线
      for (let i = 1; i < points - 1; i++) {
        // 计算当前进度（0到1之间）
        const progress = i / (points - 1);

        // 使用贝塞尔曲线原理，生成平滑曲线
        const curveFactor = Math.sin(progress * Math.PI / 2); // 曲线因子

        // 计算中间点的随机偏移
        const randomAngle = progress * Math.PI * 2 + Math.random() * 0.5;
        const randomOffset = distance * 0.2 * curveFactor * (1 - progress);

        // 计算中间点坐标
        const midX = startX + (endX - startX) * progress + Math.cos(randomAngle) * randomOffset;
        const midY = startY + (endY - startY) * progress + Math.sin(randomAngle) * randomOffset;

        track.push([midX, midY]);
      }

      // 添加终点
      track.push(endCoord);

      return track;
    },
    eventTraject(data) {
      if (this.dynamicLayer) {
        this.cleanupResources1(); // 统一清理资源
        if (this.map) {

          this.map.removeLayer(this.dynamicLayer)
        }
        this.dynamicLayer = null
      }
      this.handlerChange(data)
    },
    handlerChange(data) {
      const [x, y] = fromLonLat([this.info.lnglat[0], this.info.lnglat[1]]);
      const endCoord = [x, y];
      // const vehicleTrack = this.generateVehicleTrack(endCoord);
      const vehicleTrack = []

      data.forEach(v => {
        vehicleTrack.push(fromLonLat([v.longitude, v.latitude]))
      })
      vehicleTrack.push(endCoord)
      const layer = this.createPulseLineLayer(vehicleTrack)
      this.createPoint(data)

      this.dynamicLayer = layer
      this.map.addLayer(layer)

    },
    createPoint(data) {
      // 配置对象提取到循环外部
      const config = {
        point: {
          radius: 8,
          color: 'rgba(51, 255, 153, 1)'
        },
        heatmap: {
          radius: 7,
          blur: 12,
          gradient: [
            'rgba(0, 0, 255, 0)',
            'rgba(0, 0, 255, 0.3)',
            'rgba(0, 128, 255, 0.5)',
            'rgba(0, 255, 0, 0.6)',
            'rgba(255, 255, 0, 0.7)',
            'rgba(255, 128, 0, 0.8)',
            'rgba(255, 0, 0, 0.9)'
          ],
          minZoom: 7,
          maxRadiusAtMinZoom: 5,
          minWeightAtMinZoom: 0.3
        },
        switchZoom: 14
      };

      // 创建单个数据源并添加所有点
      const features = data.map(v => {
        const feature = new Feature({
          geometry: new Point(fromLonLat([v.longitude, v.latitude])),
          data: v, // 假设数据中包含name属性
          // 添加更多属性用于HTML显示
          longitude: v.longitude,
          latitude: v.latitude,
          // 可以添加更多属性...
        });
        return feature;
      });

      const source = new SourceVector({
        features: features
      });

      if (this.popupElement && this.popupElement.parentNode === this.map.getViewport()) {
        this.map.getViewport().removeChild(this.popupElement);
      }
      // 添加到地图容器

      // 记录当前悬停的要素
      let hoveredFeature = null;

      // 创建样式函数，移除文本标签，仅保留点样式
      const styleFunction = (feature, resolution) => {
        return [
          new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: "#8B658B" }),
            }),
          })
        ];
      };

      // 创建单个图层并使用样式函数
      const pLayer = new LayerVector({
        zIndex: 199,
        source: source,
        style: styleFunction
      });

      const popupElement = document.createElement('div');
      popupElement.className = 'ol-popup';
      popupElement.style.display = 'none';
      popupElement.style.zIndex = '1500'
      // 鼠标移动事件监听 - 显示HTML弹窗
      this.map.on('pointermove', (evt) => {
        if (evt.dragging) {
          return;
        }

        const pixel = this.map.getEventPixel(evt.originalEvent);
        let newHoveredFeature = null;

        // 创建HTML弹窗元素

        this.popupElement = popupElement
        this.map.getViewport().appendChild(this.popupElement);

        // 合并两次遍历为一次
        this.map.forEachFeatureAtPixel(pixel, (feature, layer) => {
          if (layer === pLayer) {
            newHoveredFeature = feature;
            // 更新HTML弹窗内容
            const coordinates = feature.getGeometry().getCoordinates();
            let data = feature.getProperties().data
            popupElement.innerHTML = `
          <div class="popup-content" style="background-color: rgba(0,0,0,0.7); color: white; padding: 8px; border-radius: 4px; box-shadow: 0 2px 10px rgba(0,0,0,0.2);">
            <h3 style="margin: 0 0 4px 0; border-bottom: 1px solid #ccc; padding-bottom: 4px;">车辆实时信息</h3>
            <p style="margin: 2px 0;">上报时间: ${data.collectTime}</p>
            <p style="margin: 2px 0;">速度:${data.speed}</p>
            <p style="margin: 2px 0;">方向角:${data.angle}</p>

          </div>
        `;

            // 计算弹窗位置
            const mapSize = this.map.getSize();
            const pixelPosition = this.map.getPixelFromCoordinate(coordinates);

            // 防止弹窗超出地图边界
            let left = pixelPosition[0] + 'px';
            let top = pixelPosition[1] - 30 + 'px'; // 向上偏移

            // 检查右侧边界
            if (pixelPosition[0] + 200 > mapSize[0]) {
              left = (pixelPosition[0] - 200) + 'px';
            }

            // 检查顶部边界
            if (pixelPosition[1] - 100 < 0) {
              top = (pixelPosition[1] + 30) + 'px';
            }

            // 设置弹窗位置
            popupElement.style.left = left;
            popupElement.style.top = top;
            popupElement.style.display = 'block';

            return true; // 找到第一个匹配要素后停止遍历
          }
        });

        // 只有当悬停状态真正改变时才更新
        if (newHoveredFeature !== hoveredFeature) {
          hoveredFeature = newHoveredFeature;
          // 如果没有悬停要素，隐藏弹窗
          if (!hoveredFeature) {
            popupElement.style.display = 'none';
          }
        }
      });

      // 鼠标离开地图时隐藏弹窗
      this.map.getViewport().addEventListener('mouseout', () => {
        popupElement.style.display = 'none';
        hoveredFeature = null;
      });

      this.pLayer = pLayer;
      this.map.addLayer(pLayer);
    },
    setPoint() {

      const [x, y] = fromLonLat([this.info.lnglat[0], this.info.lnglat[1]]);


      const future = new Feature({
        geometry: new Point([x, y]),
      });
      const source = new SourceVector({
        features: [future]
      });
      const config = {
        // 基础点配置
        point: {
          radius: 8,                 // 点半径
          color: 'rgba(51, 255, 153, 1)' // 点颜色
        },
        // 热力图配置
        heatmap: {
          radius: 7,
          blur: 12,
          gradient: [
            'rgba(0, 0, 255, 0)',
            'rgba(0, 0, 255, 0.3)',
            'rgba(0, 128, 255, 0.5)',
            'rgba(0, 255, 0, 0.6)',
            'rgba(255, 255, 0, 0.7)',
            'rgba(255, 128, 0, 0.8)',
            'rgba(255, 0, 0, 0.9)'
          ],
          minZoom: 7,
          maxRadiusAtMinZoom: 5,
          minWeightAtMinZoom: 0.3
        },
        // 切换阈值
        switchZoom: 14
      };
      let pointLayer = null
      let e = this.info
      if (e.standardEmission == null) {
        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: "#d4e607" }),
            }),
          })
        });
      } else if (e.standardEmission == '国三' || e.standardEmission == 'g3') {

        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: '#f95454' }),
            }),
          })
        });

      } else if ((e.standardEmission == '国四' || e.standardEmission == 'g4')) {
        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: '#ff9500' }),
            }),
          })
        });

      } else if ((e.standardEmission == '国五' || e.standardEmission == 'g5')) {
        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: '#d4e607' }),
            }),
          })
        });
      } else if (e.standardEmission == '国六' || e.standardEmission == 'g6') {
        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: '#07e7f3' }),
            }),
          })
        });
      } else if ((e.standardEmission == '新能源' || e.standardEmission == 'xny')) {
        pointLayer = new LayerVector({
          zIndex: 299,

          source: source,
          style: new Style({
            image: new CircleStyle({
              radius: config.point.radius,
              fill: new Fill({ color: '#07e6ac' }),
            }),
          })
        });
      }

      this.map.addLayer(pointLayer);

    },
    async initMap() {
      const p2 = await this.initTiandituMap()
    },
    async initTiandituMap() {


      const that = this;
      const url_Vector = "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=" + this.key


      function modifyTileColor(image) {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const ctx = canvas.getContext('2d');

        // 绘制原始图像
        ctx.drawImage(image, 0, 0);

        // 设置合成操作，这里使用 'multiply' 模式，可根据需求调整
        ctx.globalCompositeOperation = 'multiply';

        // 设置蒙版颜色，这里使用你之前提到的科技感蓝色
        ctx.fillStyle = 'rgb(70, 99, 153)';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 恢复默认合成操作
        ctx.globalCompositeOperation = 'source-over';

        return canvas;
      }


      let layer1 = new TileLayer({
        source: new XYZ({
          wrapX: false,
        }),

      })
      this.layers.push(layer1)

      const lon = this.info.lnglat[0]
      const lat = this.info.lnglat[1]

      const m = this.$refs.map;
      const map = new Map({
        target: m,
        layers: [layer1],
        controls: [],
        view: new View({
          projection: "EPSG:3857",
          center: fromLonLat([lon, lat]),
          smoothResolutionConstraint: true,
          minZoom: 11,
          zoom: 15,
          maxZoom: 16
        })
      });

      that.map = map

      // const url_Vector_MARK = "http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=" + this.key
      // let layer2 = new TileLayer({
      //   source: new XYZ({
      //     url: url_Vector_MARK,
      //     wrapX: false

      //   }),
      // })
      // that.map.addLayer(layer2)
    },
    /*创建地图*/
    initCompanyIcon() {
      const that = this
      let s = []
      let s1 = []

      that.enterprises.forEach(e => {
        const coordinates = e.geojson[0][0].map(([lng, lat]) => fromLonLat([lng, lat]));
        const polygonGeometry = new Polygon([coordinates]);

        const polygonFeature = new Feature({
          geometry: polygonGeometry
        });

        const polygonStyle = new Style({
          // stroke: new Stroke({
          // 	// color: '#74F4F9',
          // 	color: 'rgba(223,153,54)',
          // 	width: 2.2
          // }),
          // fill: new Fill({
          // 	color: 'rgba(0, 255, 255, 0.4)'
          // 	// color: 'rgba(247, 247, 247)'

          // })
          stroke: new Stroke({
            color: 'rgb(7, 245, 197)',
            width: 1
          }),
          fill: new Fill({
            color: 'rgba(0, 255, 255,0.1)'
          }),
        });

        polygonFeature.setStyle(polygonStyle);

        const vectorSource = new SourceVector({
          features: [polygonFeature]
        });

        const vectorLayer = new LayerVector({
          source: vectorSource
        });
        if (that.map) {
          that.map.addLayer(vectorLayer);

        }



        e.children.forEach(e => {


          function calculateCentroid(coordinates) {
            let sumX = 0;
            let sumY = 0;
            const points = coordinates[0][0]; // 提取实际的坐标点数组

            for (const point of points) {
              sumX += point[0]; // 经度
              sumY += point[1]; // 纬度
            }

            return {
              lon: sumX / points.length,
              lat: sumY / points.length
            };
          }
          if(e.geom == null){
            return
          }
          const { lon, lat } = calculateCentroid(e.geom.coordinates)
          const innerPolygonCoordinates1 = e.geom.coordinates[0][0].map(([lng, lat]) => {
            const c = fromLonLat([lng, lat]);

            return c;
          });

          s.push(innerPolygonCoordinates1)
          const icon = new Icon({
            anchor: [0.5, 1],
            src: that.iconDevice,
            scale: 0.9,

          })
          const iconFeature = new Feature({
            geometry: new Point(fromLonLat([lon, lat])),
            name: e.name,
            address: e.detailedAddress,
            regionId: e.regionId
          });
          const iconStyle = new Style({
						text: new Text({
							text: e.name, // 企业名称
							font: '14px Arial', // 字体样式
							fill: new Fill({ color: '#FFFFFF' }), // 文本颜色
							stroke: new Stroke({ color: '#000000', width: 1 }), // 文本描边（提高可读性）
							// offsetY: -45, // 文本在 Y 轴上的偏移（负值表示向上）
							textAlign: 'center', // 文本对齐方式
							// backgroundFill: new Fill({ color: 'rgba(0, 0, 0, 0.7)' }), // 文本背景
							padding: [5, 10, 5, 10],// 文本内边距 [上, 右, 下, 左]
						})
					});

          iconFeature.setStyle(iconStyle);

          const vectorSource_ = new SourceVector({
            features: [iconFeature]
          });

          const vectorLayer_ = new LayerVector({
            source: vectorSource_,
            visible: false
          });

          s1.push(vectorLayer_)
        })
      })

      const polygons = s.map(coords => new Polygon([coords]));


      const source = new SourceVector({
        features: polygons.map(polygon => {
          const feature = new Feature({
            geometry: polygon
          });
          return feature;
        })
      });

      // 创建样式
      const style = new Style({
        stroke: new Stroke({
          color: '#00FFFF',
          width: 3
        }),
        // fill: new Fill({
        //   color: 'rgba(7, 43, 76, 0.3)'
        // }),
        // stroke: new Stroke({
        // 	color: 'rgba(134,63,192)',
        // 	width: 4
        // }),
        // fill: new Fill({
        // 	color: 'rgba(12,73 172)'
        // })
      });

      // 创建矢量图层
      const vectorLayer = new LayerVector({
        source: source,
        style: style
      });

      if (that.map) {
        that.map.addLayer(vectorLayer);

      }
      // 添加图层到地图


      s1.forEach(vectorLayer_ => {
        if (that.map) {

          that.map.addLayer(vectorLayer_);
        }
        // that.map.getView().on('change:resolution', function () {
        //   const zoom = that.map.getView().getZoom();

        //   // 只在缩放级别≥8时显示
        // vectorLayer_.setVisible(zoom >= 10);
        vectorLayer_.setVisible(true)
        // });
      })

      if (that.map) {
        that.map.on("click", function (e) {
          var pixel = that.map.getEventPixel(e.originalEvent);
          var currentLayer = null
          var feature = that.map.forEachFeatureAtPixel(pixel, function (feature, layer) {
            currentLayer = layer;
            return feature;
          })
          if (feature != undefined && feature.get('regionId') != undefined) {
            // if (that.overlay && feature.get('regionId') == that.overlay.get('regionId')) {
            // 	return
            // }
            that.map.removeOverlay(that.overlay)
            that.openInfoWindow(feature)
          } else {
            if (that.overlay == undefined) {
              return
            }
            that.map.removeOverlay(that.overlay)
          }
        })
      }



    },
    closeInfoWindow() {
      this.map.removeOverlay(this.overlay);
    },
    /*室内停靠点*/
    openInfoWindow(e) {
      var name = e.get('name')
      var address = e.get('address')
      var regionId = e.get('regionId')
      const info = []
      //标题
      info.push('<div style="width: 250px;height: 30px;line-height:30px;padding:0px 0px 0px 10px;color:#ffffff;border-radius: 5px 5px 0 0;background-color:#00aaff;opacity: 0.9;font-size: 16px;">概要信息<span id="infoWindow" style="width:40px;text-align: center;float:right;" onclick="window.modalMap.closeInfoWindow()">x</span></div>');
      //内容-start
      info.push('<div style="width: 250px;height: auto;padding:10px;border-radius: 0px 0px 5px 5px;background-color:#003c5a;opacity: 0.9;font-size: 14px;display: flex;flex-direction: column;">');

      info.push('<div id="" style="width: 100%;color:#00aaff;height: auto;">名称：');
      info.push('<span style="color:#56d9c8;">' + name + '</span>');
      info.push('</div>');

      info.push('<div id="" style="width: 100%;color:#00aaff;height: auto;margin-top:5px;">地址：');
      info.push('<span style="color:#56d9c8;">' + address + '</span>');
      info.push('</div>');

      info.push('</div>');

      var element = document.createElement('div');
      element.className = 'ol-popup';
      element.innerHTML = info.join("");
      element.style.cursor = 'pointer'; // 设置鼠标悬停时变为手型

      // 创建 OpenLayers 的 Overlay 对象
      var overlay = new Overlay({
        element: element,
        positioning: 'bottom-center',
        stopEvent: true,
        offset: [0, -10],
      });
      var coordinate = e.getGeometry().getCoordinates();
      overlay.setPosition(coordinate);
      this.map.addOverlay(overlay);
      this.overlay = overlay

    },
    setIcon() {
      let markers = []
      let tmp = this.points || []
      if (tmp.length <= 0) {
        return false
      }
      for (const v of tmp) {
        let lnglat = gcoord.transform([v.lon, v.lat], gcoord.WGS84, gcoord.GCJ02)
        let mk = new AMap.Marker({
          icon: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png',
          position: lnglat,
          anchor: 'center',
          size: 20,
          offset: new AMap.Pixel(0, 0)
        })
        markers.push(mk)
        mk.on("mouseover", () => {
          if (v.stopStation) {
            this.openInfo(v.stopStation, lnglat)
          }
        });
        mk.on("mouseout", () => {
          if (v.stopStation) {
            infoWindow.close();
          }
        });
      }
      markerGroup = new AMap.OverlayGroup(markers)
      map.add(markerGroup)
    },
    /*清除点线*/
    clearLoca() {
      loca.remove(todayLayer)
      loca.remove(prev15DayPointLayer)
      prev15DayLayer && map.remove(prev15DayLayer)
      markerGroup && map.remove(markerGroup)
      massLayer && massLayer.remove(prev15DayPointLayer)
    },
    /*行为画像大量点*/
    setLocaIcon() {
      let data = this.prev15DayPoints
      massLayer = new AMap.LabelsLayer({
        zooms: [8, 20],
        zIndex: 1000,
        collision: false
      });
      map.add(massLayer)
      prev15DayPointLayer = []
      let tmp = data.features || []
      if (tmp.length <= 0) {
        return false
      }
      for (const v of tmp) {
        let lnglat = [v.geometry.coordinates[0], v.geometry.coordinates[1]]
        let mk = new AMap.LabelMarker({
          icon: {
            type: 'image',
            image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
            size: [25, 30],
            anchor: 'center',
          },
          position: lnglat,
          opacity: 0.8,
          zooms: [8, 20],
          extData: v.properties,
          anchor: 'center',
        })
        prev15DayPointLayer.push(mk)
        mk.on("mouseover", (e) => {
          this.openInfo(e.target._opts.extData, lnglat)
        });
        mk.on("mouseout", (e) => {
          infoWindow.close();
        });
      }
      massLayer.add(prev15DayPointLayer)

    },
    setLine(line = 1) {
      this.clearLoca()
      // 今天轨迹
      if (line === 1 && this.todayLine.type) {
        todayLayer = this.setLocaPulseLine(this.todayLine)
        loca.add(todayLayer)
        loca.animate.start()
      }
      // 15天轨迹
      if (line === 2 && this.prev15DayLine.type) {
        prev15DayLayer = this.setLocaLine(this.prev15DayLine)
        map.add(prev15DayLayer)
        this.setLocaIcon()
      }
    },
    /*15天轨迹*/
    setLocaLine($data) {
      let data = $data
      let arry = []
      for (let obj of data.features) {
        let arry2 = []
        for (let obj2 of obj.geometry.coordinates) {
          arry2.push(obj2)
        }
        arry.push(arry2)
      }
      let lineLayer = new AMap.Polyline({
        showDir: true,
        path: arry,
        zIndex: 100,
        strokeOpacity: 1,
        strokeColor: 'blue',
        strokeWeight: 8,
        borderWeight: 1,
      })
      return lineLayer
    },
    /*今天轨迹画像*/
    setLocaPulseLine($data) {
      let data = $data
      let geo = new Loca.GeoJSONSource({
        data
      })
      let layer = new Loca.PulseLineLayer({
        // loca,
        zIndex: 100,
        opacity: 1,
        visible: true,
        zooms: [2, 22]
      })
      layer.setSource(geo)
      layer.setStyle({
        altitude: 0,
        lineWidth: 4,
        // 脉冲头颜色
        headColor: '#00ffff',
        // 脉冲尾颜色
        trailColor: '#808080ff',
        // 脉冲长度，0.25 表示一段脉冲占整条路的 1/4
        interval: 0.25,
        // 脉冲线的速度，几秒钟跑完整段路
        duration: 5000
      })
      return layer
    },
    setMarker() {
      if (!this.info.lnglat || this.info.lnglat.length <= 0) {
        return false
      }
      let LngLats = gcoord.transform(
        this.info.lnglat,    // 经纬度坐标
        gcoord.WGS84,                 // 当前坐标系
        gcoord.GCJ02                   // 目标坐标系
      )
      if (!LngLats) {
        return false
      }
      let html = `
<div class="map-large-dot ripples" style="color: #00ffff">
   <div class="circle"></div>
   <div class="circle"></div>
   <div class="circle"></div>
   <div class="circle"></div>
</div>
      `
      marker && map.remove(marker)
      marker = new AMap.Marker({
        position: LngLats,
        content: html,
        offset: new AMap.Pixel(-13, -30)
      })
      map.add(marker)
      map.setFitView()
      map.setZoom(11)
    },
    //在指定位置打开信息窗体
    openInfo(value, myposition) {
      //构建信息窗体中显示的内容
      let info = ''
      let myOffset = 0
      if (typeof value === 'string') {
        myOffset = -40
        info = `
              <div style="border-radius: 5px;padding:10px;background: #ffffff26;color: #fff;border: 1px solid #00ffff88;">${value}</div>
        `
      } else if (typeof value === 'object') {
        myOffset = -15
        info = `
              <div style="border-radius: 5px;padding:10px;background: #ffffff26;color: #fff;border: 1px solid #00ffff88;">
                ${value.collect_time}
                <br>
                速度 : ${value.speed}
                <br>
                转向角 : ${value.angle}
              </div>
        `
      }


      infoWindow = new AMap.InfoWindow({
        content: info,  //使用默认信息窗体框样式，显示信息内容
        anchor: 'bottom-center',
        offset: new AMap.Pixel(0, myOffset),
        isCustom: true,
      });

      infoWindow.open(map, myposition);
    },
    // 控制图例显示隐藏
    setLayerContrls() {
      this.layerActive = !this.layerActive
    },
    // 点击图例的回调
    changeLayer2(e) {
      if (e.tag !== 0 && e.name !== this.actives2) {
        if (e.name === '卫星路网底图') {
          // 卫星
          satellite = new AMap.TileLayer.Satellite()
          // 路网
          roadnet = new AMap.TileLayer.RoadNet()
          map.addLayer(satellite);
          map.addLayer(roadnet);
        } else if (e.tag === 1) {
          satellite && map.remove(satellite)
          roadnet && map.remove(roadnet)
          this.mapStyle = e.params.url
          map.setMapStyle(e.params.url);
        }

        if (e.name === '企业围栏') {
          let pars = Groups2.filter(e => {
            return e.name === '企业围栏'
          })
          WMS7Layer = this.setWMSLayer(pars[0].params)
          map.add(WMS7Layer)
        }

        if (e.name === '卫星2020') {
          let pars = Groups2.filter(e => {
            return e.name === '卫星2020'
          })
          WMS5Layer = this.setWMSLayer(pars[0].params)
          map.add(WMS5Layer)
        }

        if (e.name === '卫星2017') {
          let pars = Groups2.filter(e => {
            return e.name === '卫星2017'
          })
          WMS6Layer = this.setWMSLayer(pars[0].params)
          map.add(WMS6Layer)
        }
        this.actives2 = e.name
      }
    },
    setWMSLayer(params = {}, show = true) {
      // let url = 'http://192.168.152.152:9080/geoserver/cycemi/wms'
      return new AMap.TileLayer({
        tileSize: 256,
        getTileUrl: function (x, y, z) {  //v1.4to v2 change line line
          let xmin = tile2lon(x, z);
          let xmax = tile2lon(x + 1, z);
          let ymin = tile2lat(y + 1, z);
          let ymax = tile2lat(y, z);

          // 转换对应坐标
          let t1 = gcoord.transform([xmin, ymin], gcoord.GCJ02, gcoord.EPSG3857);
          let t2 = gcoord.transform([xmax, ymax], gcoord.GCJ02, gcoord.EPSG3857);

          // 查询对象
          // let url = 'http://192.168.152.152:9080/geoserver/cycemi/wms?'
          let pars = {
            service: "WMS",
            version: "1.1.0",
            transparent: true,
            request: "GetMap",
            layers: params.LAYERS,
            width: 256,
            height: 256,
            srs: "EPSG:3857",
            format: "image/png",
            bbox: [t1[0], t1[1], t2[0], t2[1]].join(',')
          }
          // 构建查询字符串
          let str = urlEncode(pars)
          return params.url + str
        },
        zIndex: 10
      })
    },
  }
}
</script>

<style scoped lang="scss">
@keyframes radar {
  from {
    opacity: 1;
    transform: scale(0);
  }

  to {
    opacity: 0;
    transform: scale(3);
  }
}

.map-box {
  position: relative;
}

.layer-btn {
  width: 59px;
  height: 40px;
  background: #00000022;
  border: 1px solid #ffffff44;
  position: absolute;
  top: 50px;
  right: 40px;
  z-index: 999999;
  padding: 5px;
  background: url("~@/assets/images/layer.svg") no-repeat center center;
  background-size: 25px 23px;
  cursor: pointer;

  &.active {
    background: url("~@/assets/images/layer-.svg") no-repeat center center;
    background-size: 25px 23px;
  }
}

.map-lengend {
  position: absolute;
  right: 40px;
  bottom: 160px;
  z-index: 100;
  color: #9bc1d1;
  background: #00000055;
  padding: 15px;
  border-radius: 12px;

  .lengend-item {
    display: flex;
    padding: 5px 10px;
    cursor: pointer;

    .dot {
      width: 20px;
      height: 20px;
      display: inline-block;
      border-radius: 20px;
      margin-right: 10px;
    }
  }
}

.map {
  width: calc(100vw * 0.9 * 0.55);
  height: 830px;
  position: relative;

  ::v-deep .map-large-dot {
    &.ripples {
      margin: 0 auto;
      width: 50px;
      height: 50px;
      position: relative;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #ffffff00;
      border-radius: 50%;

      .circle {
        position: absolute;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: currentColor;

        &:nth-child(1) {
          animation: radar 3s linear infinite;
        }

        &:nth-child(2) {
          animation: radar 3s linear 0.8s infinite;
        }

        &e:nth-child(3) {
          animation: radar 3s linear 1.6s infinite;
        }
      }
    }
  }

}

.map_menu1 {
  position: absolute;
  z-index: 1;
  right: 5vw;
  bottom: 1vh;
  /*
		background-color: rgba(97, 118, 131, 1);
		*/
  border-radius: 5px;
  display: flex;
}
</style>
